package com.ruoyi.controller;


import com.ruoyi.bole.integral.domain.BoleIntegralApplication;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.domain.TaskDTO;
import com.ruoyi.service.ProcessService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class BoleIntegralEngingController {

    @Autowired
    private ProcessService processService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    @Log(title = "积分申请", businessType = BusinessType.INSERT)
    @PostMapping("/engin/integralAdd")
    public AjaxResult add(@RequestBody BoleIntegralApplication boleIntegralApplication)
    {
        processService.startProcessForIntegral(boleIntegralApplication, "integralProcess");
        return AjaxResult.success();
    }
    @GetMapping("/taskIntegral/list")
    public List<TaskDTO> getTasks() {
        List<SysRole> roleList = SecurityUtils.getLoginUser().getUser().getRoles();
        Collection<String> roles = roleList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        // 查询原始任务列表
        List<Task> tasks = taskService.createTaskQuery()
                .taskAssigneeIn(roles.toArray(new String[0]))
                .list();
        return tasks.stream().map(task -> {
            TaskDTO dto = new TaskDTO();
            dto.setId(task.getId());
            dto.setName(task.getName());
            dto.setAssignee(task.getAssignee());
            dto.setCreateTime(task.getCreateTime());

            // 获取流程实例ID（通过任务获取流程实例ID）
            String processInstanceId = task.getProcessInstanceId();

            // 通过流程实例ID获取流程变量（包括dataId）
            Map<String, Object> variables = runtimeService.getVariables(processInstanceId);
            Long dataId = (Long) variables.get("integralId"); // 提取业务数据ID
            dto.setIntegralId(String.valueOf(dataId)); // 将dataId存入DTO
//            query.taskAssigneeIn(assignees.toArray(new String[0]))
            return dto;
        }).collect(Collectors.toList());
    }
}
